package com.tina.tinasso.service;

import com.auth0.jwt.interfaces.Claim;
import com.tina.tinasso.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Tina
 * @version 0.0.1
 * @date 2020/7/2 16:30
 **/
@Service
public class JwtService {

    public static final String JWT_KEY = "jwt_token";

    private Logger logger = LoggerFactory.getLogger(JwtService.class);

    @Autowired
    private RedisUtil redisUtil;


    /**
     * Description:登录获取token
     *
     * @param phone 手机号码
     * @return java.lang.String
     */
    public ResultFormat login(String phone, Integer captcha) {
        if (!ShortMessageUtil.isMobileNO(phone)) {
            return ResultUtil.error(100, "手机号输入错误");
        }
        if (captcha != null) {
            Integer str = (Integer) redisUtil.get(phone + ":" + captcha);
            System.out.println(str);
            if (str != null) {
                if (str.equals(captcha)) {
                    return ResultUtil.success("认证成功", this.generateNewJwt(phone));
                }
            } else {
                return ResultUtil.error(100, "验证码无效");
            }
        }
        return ResultUtil.error();

    }

    /**
     * jwt token超时时间，单位ms
     */
    private static int expireTime;

    @Value("${jwt_expire_time}")
    public void setExpireTime(int expireTime) {
        JwtService.expireTime = expireTime * 60 * 1000;
    }


    /**
     * 过期时间小于半小时，返回新的jwt，否则返回原jwt
     *
     * @param jwt
     * @return
     */
    public String refreshJwt(String jwt) {
        String secret = (String) redisUtil.get(jwt);
        Map<String, Claim> map = JwtUtil.decode(jwt, secret);
        if (map.get("exp").asLong() * 1000 - System.currentTimeMillis() / 1000 < 30 * 60 * 1000) {
            return this.generateNewJwt(map.get("name").asString());
        } else {
            return jwt;
        }
    }


    /**
     * Description: 生成新的jwt,并放入jwtMap中
     *
     * @return java.lang.String
     */
    private String generateNewJwt(String name) {
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        String token = JwtUtil.encode(name, secret, expireTime);
        redisUtil.set(token, secret, expireTime);
        return token;
    }

    /**
     * Description:检查jwt有效性
     *
     * @return Boolean
     */
    public Boolean checkJwt(String jwt) {
        try {
            String secret = (String) redisUtil.get(jwt);
            JwtUtil.decode(jwt, secret);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Description: 使该jwt失效
     */
    public void inValid(String jwt) {
        redisUtil.delete(jwt);
    }

}
